package org.example.movies.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/CheckCodeController")
public class CheckCodeController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //建立一个长、高的图片
        int width=100;
        int hight=50;
        //创建带缓冲区的图片对象,需要传递宽、高、图片颜色的类型
        BufferedImage buf = new BufferedImage(width,hight,BufferedImage.TYPE_INT_RGB);
        //通过图片对象获取画笔
        Graphics gs = buf.getGraphics();
        //给画笔设置颜色
        gs.setColor(Color.black);
        //通过画笔给图片填充颜色
        gs.fillRect(0,0,width,hight);
        //给画笔来设置颜色
        gs.setColor(Color.pink);
        //设置字体
        gs.setFont(new Font("黑体",Font.BOLD,20));
        //生成随机数当验证
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        int code=0;
        for (int i=0;i<4;i++){
            code=random.nextInt(10);
            sb.append(code);
            //把随机数加进图片中
            gs.drawString(code+"",15+20*i,30);
        }
        //把验证码放到session作用域中
        HttpSession session = request.getSession();
        String action = request.getParameter("action");
        action = action.substring(0, 5);
        if ("regis".equals(action)) {
            session.setAttribute("register", sb.toString());
        } else if ("login".equals(action)) {
            session.setAttribute("login", sb.toString());
        }
        //设置画笔颜色
        gs.setColor(Color.RED);
        //设置干扰线
        for (int i=0;i<10;i++){
            gs.drawLine(random.nextInt(width),random.nextInt(hight),random.nextInt(width),random.nextInt(hight));
        }
        //把绘制好的图片响应给客户端
        ImageIO.write(buf,"jpg",response.getOutputStream());
    }
}
